// 对话框模块
import { dialog, ipcMain, BrowserWindow } from 'electron'
import type { IpcMainInvokeEvent, OpenDialogOptions } from 'electron'

// 选择文件
ipcMain.handle('selectMultiFile', async (event: IpcMainInvokeEvent) => {
  return showOpenDialog(event, {
    title: '选择文件',
    properties: ['openFile', 'multiSelections']
  })
})

// 选择文件夹
ipcMain.handle('selectMultiFolder', (event: IpcMainInvokeEvent) => {
  return showOpenDialog(event, {
    title: '选择文件夹',
    properties: ['openDirectory', 'multiSelections']
  })
})

// 选择单个文件夹
ipcMain.handle('selectSingleFolder', async (event: IpcMainInvokeEvent) => {
  const target = await showOpenDialog(event, {
    title: '选择文件夹',
    properties: ['openDirectory']
  })
  return target[0]
})

const showOpenDialog = async (
  event: IpcMainInvokeEvent,
  options: OpenDialogOptions
) => {
  const { canceled, filePaths } = await dialog.showOpenDialog(
    BrowserWindow.fromWebContents(event.sender)!,
    options
  )
  if (!canceled && filePaths.length > 0) {
    return filePaths
  }
  return []
}
